<?php

namespace app\webapi\controller;

use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;

class ApiUserGoods extends ApiBaseController
{
    public $user_info = null;

    public function __construct()
    {
        $this->user_info = $this->checkToken();
        if (!preg_match('/^\d+$/', $this->user_info['id'])) {
            $this->result_error('用户id出错');
        }
    }

    /** 货架商品详情【2】 */
    public function getGoodsDetail()
    {
        $gid = (int)Request::param('gid');
        if (!($gid > 0)) {
            $this->result_error('商品id错误');
        }
//        $goodsInfo = Cache::store('redis')->hGet(self::KEYS['SHELVES_GOODS'] . '0', $gid);
        $goodsInfo = APiRedisServer::selected(3)->hGet(self::KEYS['SHELVES_GOODS'] . '0', $gid);
        if (empty($goodsInfo)) {
            $this->result_error("该商品未上架");
        } else {
            $this->result_ok("ok", json_decode($goodsInfo));
        }
    }

    /** 我的商品 */
    public function myGoods()
    {
        $sql = "SELECT a.gid,a.name,a.rusher_id,b.phone buyer_name,a.price,a.img,a.state,a.update_time 
                FROM sy_goods_rush a 
                LEFT JOIN sy_user b ON a.rusher_id=b.id 
                WHERE a.belong=? AND a.state>=0 
                ORDER BY a.gid DESC";
        $sql_result = Db::query($sql, [$this->user_info['id']]);
        $this->result_ok("ok", $sql_result[0]);
    }

    /** 我的已支付待确认的商品 */
    public function myPayedGoods()
    {
        $sql = "SELECT a.gid,a.name,a.rusher_id,b.phone saler_name,a.price,a.img,a.state,a.update_time 
                FROM sy_goods_rush a 
                LEFT JOIN sy_user b ON a.belong=b.id 
                WHERE a.rusher_id=? AND a.state=3 
                ORDER BY a.update_time DESC";
        $sql_result = Db::query($sql, [$this->user_info['id']]);
        $this->result_ok("ok", $sql_result[0]);
    }

    /** 货架商品添加到购物车【2】 */
    public function addCart()
    {
        $gid = (int)Request::param('gid');
        if (!($gid > 0)) {
            $this->result_error('商品id错误');
        }
        $sql_result = Db::name('user_cart')->where('uid', $this->user_info['id'])->where('gid', $gid)->select()->toArray();
        if (!empty($sql_result)) {
            $res = Db::name('user_cart')->where('uid', $this->user_info['id'])->where('gid', $gid)->inc('count')->update([]);
        } else {
            $res = Db::name('user_cart')->insertGetId([
                'uid' => $this->user_info['id'],
                'gid' => $gid,
                'count' => 1,
                'selected' => 1
            ]);
        }
        if ($res) {
            $this->result_ok('添加成功');
        }
        $this->result_error('添加失败');
    }

    /** 我的购物车列表【2】 */
    public function myCartList()
    {
        $sql_result = Db::name('user_cart')->where('uid', $this->user_info['id'])->order('create_time', 'desc')->select()->toArray();
        if (empty($sql_result)) {
            $this->result_ok('ok', []);
        }
        $gidkeys = array_column($sql_result, 'gid');
//        $alldata = Cache::store('redis')->hmGet(self::KEYS['SHELVES_GOODS'] . '0', $gidkeys);
        $alldata = APiRedisServer::selected(3)->hmGet(self::KEYS['SHELVES_GOODS'] . '0', $gidkeys);

        $alldata = array_filter($alldata, function ($item) {
            return !empty($item);
        });
        if (empty($alldata)) {
            $this->result_ok('ok', []);
        }
        foreach ($alldata as &$v) {
            $v = json_decode($v, true);
        }
//        $remain = Cache::store('redis')->hmGet(self::KEYS['SHELVES_GOODS_COUNTER']);
        $remain = APiRedisServer::selected(3)->hGetAll(self::KEYS['SHELVES_GOODS_COUNTER']);
        $data = array();
        foreach ($sql_result as $value) {
            $fd = array_filter($alldata, function ($item) use ($value) {
                return $item['id'] == $value['gid'];
            });
//            echo "<pre>";
//            var_dump(reset($fd));
            $obj = array_merge($value, reset($fd), ['goods_count' => (int)$remain[$value['gid']]]);
//            var_dump($obj);die;
            $data[] = $obj;
        }
        $this->result_ok('ok', $data);

    }

    /** 将商品移除购物车【2】 */
    public function removeCart()
    {
        $gid = (int)Request::param('gid');
        if (!($gid > 0)) {
            $this->result_error('商品id错误');
        }
        $sql_result = Db::name('user_cart')->where('uid', $this->user_info['id'])->where('gid', $gid)->delete();
        if ($sql_result) {
            $this->result_ok('移除成功');
        }
        $this->result_error('移除失败');
    }

    /** 批量将商品移除购物车【2】 */
    public function removeCartBatch()
    {
        $ids = Request::param('ids');
        if (!(count($ids) > 0)) {
            $this->result_error('参数错误');
        }
        $sql_result = Db::name('user_cart')->where('uid', $this->user_info['id'])->whereIn('gid', $ids)->delete();
        if ($sql_result) {
            $this->result_ok('移除成功');
        }
        $this->result_error('移除失败');
    }

    /** 更新购物车数量【2】 */
    public function updateCart()
    {
        $gid = (int)Request::param('gid');
        $count = (int)Request::param('count');
        $selected = (int)Request::param('selected');
        if (!($gid > 0)) {
            $this->result_error('商品id错误');
        }
        if (!($count > 0)) {
            $this->result_error('商品数量错误');
        }
        if (!preg_match("/^[0-9]*$/", $gid)) {
            $this->result_error('商品id出错');
        }
        if (!preg_match("/^[0-9]*$/", $count)) {
            $this->result_error('商品数量出错');
        }
        if ($selected != 0 && $selected != 1) {
            $this->result_error('商品选择状态错误');
        }
        $up_res = Db::name('user_cart')
            ->where('uid', $this->user_info['id'])
            ->where('gid', $gid)
            ->update([
                'count' => $count,
                'selected' => $selected
            ]);
        $this->result_ok('ok');


    }

    /** 我是买方（商品列表） */
    public function imBuyer()
    {
        $sql = "SELECT a.*,b.id as order_id,b.order_no,c.payee_name,c.payee_bankname,c.payee_bankno,c.avatar belong_avatar,c.nickname belong_nickname,c.wxpay_img,c.alipay_img,
                d.avatar rusher_avatar,d.nickname rusher_nickname,e.avatar last_belong_avatar,e.nickname last_belong_nickname 
                FROM sy_goods_rush a 
                LEFT JOIN sy_user_order b ON a.current_order_id=b.id 
                LEFT JOIN sy_user c ON c.id=a.belong  
                LEFT JOIN sy_user d ON d.id=a.rusher_id   
                LEFT JOIN sy_user e ON e.id=a.last_belong   
                WHERE (a.belong=? AND a.state IN (0,1,6)) OR (a.rusher_id=? AND a.state IN (2,3,5)) 
                ORDER BY b.create_time DESC";
        $sql_result = Db::query($sql, [$this->user_info['id'], $this->user_info['id']]);
        $gids = array_column($sql_result, 'id');
        if (count($gids) > 0) {
            $schedules = Db::name('goods_rush_schedule_map')->alias('a')->join('sy_rush_schedule b','a.sid = b.id')->whereIn('a.gid',$gids)->field('a.gid,b.name')->select()->toArray();
            $map = array();
            foreach ($schedules as $v) {
                $map[$v['gid']] = $v['name'];
            }
            if (!empty($map)) {
                foreach ($sql_result as &$sv) {
                    $sv['schedule_name'] = $map[$sv['id']]??'';
                }
            }

        }
        $this->result_ok('ok', $sql_result);

    }

    /** 我是卖方（商品列表）  */
    public function imSaler()
    {
        $sql = "SELECT a.*,b.id as order_id,b.order_no 
    FROM sy_goods_rush a 
    LEFT JOIN sy_user_order b ON a.current_order_id=b.id 
    WHERE (a.belong=? AND a.state IN (1,2,3,5,6))";
        $sql_result = Db::query($sql, [$this->user_info['id']]);
        $gids = array_column($sql_result, 'id');
        if (count($gids) > 0) {
            $schedules = Db::name('goods_rush_schedule_map')->alias('a')->join('sy_rush_schedule b','a.sid = b.id')->whereIn('a.gid',$gids)->field('a.gid,b.name')->select()->toArray();
            $map = array();
            foreach ($schedules as $v) {
                $map[$v['gid']] = $v['name'];
            }
            if (!empty($map)) {
                foreach ($sql_result as &$sv) {
                    $sv['schedule_name'] = $map[$sv['id']]??'';
                }
            }

        }
        $this->result_ok('ok', $sql_result);
    }

    /** 查看支付截图 */
    public function viewPayImg()
    {
        $uid = (int)Request::param('uid');
        $order_id = (int)Request::param('order_id');
        if (!($uid > 0)) {
            $this->result_error('参数错误');
        }
        if (!($order_id > 0)) {
            $this->result_error('订单号错误');
        }
        if (!preg_match("/^[0-9]*$/", $uid)) {
            $this->result_error('用户id出错');
        }
        $sql_result = Db::name('user_order_payimg')->where('uid', $uid)->where('order_id', $order_id)->select()->toArray();
        $this->result_ok('ok', $sql_result);

    }

    /** 提货 */
    public function giveMe()
    {
        $gid = (int)Request::param('gid');
        if (!($gid > 0)) {
            $this->result_error('参数错误');
        }
        $sql_result = Db::name('goods_rush')
            ->where('belong', $this->user_info['id'])
            ->where('state', 0)
            ->where('id', $gid)
            ->update(['state' => 6]);

        if ($sql_result) {
            $this->result_ok('提货成功');
        }
        $this->result_error("提货失败");
    }

    /** 取消订单【2】 */
    public function cancelOrder()
    {
        $gid = (int)Request::param('gid');
        $order_id = (int)Request::param('order_id');
        if (!($gid > 0)) {
            $this->result_error('商品id错误');
        }
        if (!($order_id > 0)) {
            $this->result_error('订单id错误');
        }
        $order_info = Db::name('user_order')
            ->where('id', $order_id)
            ->where('uid', $this->user_info['id'])
            ->find();
        if (empty($order_info)) {
            $this->result_error('取消失败,没有找到订单');
        }
        // 启动事务
        Db::startTrans();
        try{
            $sql_result = Db::name('goods_rush')
                ->where('rusher_id', $this->user_info['id'])
                ->where('state', 2)
                ->where('id', $gid)
                ->where('current_order_id', $order_id)
                ->update(['state' => 1, 'rusher_id' => 0]);
            // 提交事务
            $sql = "SELECT a.*,b.nickname belong_nickname,b.avatar belong_avatar 
                    FROM sy_goods_rush a 
                    LEFT JOIN sy_user b ON b.id=a.belong 
                    WHERE a.id=?";
            $goodsinfo = Db::query($sql, [$gid]);
            APiRedisServer::selected(0)->hSet(self::KEYS['RUSH_GOODS'] . $order_info['schedule_id'], $gid, json_encode($goodsinfo[0]));
            $upres = Db::execute("UPDATE sy_user_order SET state=-1 WHERE id=? AND uid=?", [$order_id, $this->user_info['id']]);
            APiRedisServer::selected(0)->hSet(self::KEYS['RUSH_GOODS_COUNTER'] . $order_info['schedule_id'], $gid, '1');
            if($sql_result && $upres){
                Db::commit();
                $this->result_ok('取消成功');
            }else{
                Db::rollback();
                $this->result_error("取消失败");
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->result_error("取消失败");
        }


    }

    /** 我的商品 */
    public function myFavGoods()
    {
        $uid = $this->user_info['id'];
        $arr1 = $this->getMyShelvesGoods($uid);
        $arr2 = $this->getMyRushGoods($uid);
        $arr = array_merge($arr1, $arr2);
        usort($arr, function ($current, $next) {
            return $next['create_time'] > $current['create_time'];
        });
        $this->result_ok('ok', $arr);
    }

    /** 获取我货架上购买的商品 */
    public function getMyShelvesGoods($uid)
    {
        $sql = "SELECT a.id as order_id,a.order_no,a.create_time,a.goods_info,a.price order_price,b.parcel 
                FROM sy_user_order_shelves a 
                LEFT JOIN sy_user_parcel b ON b.order_from=1 AND b.order_id=a.id
                WHERE a.uid=? AND a.state=1 AND a.pay_state=1";

        $orderlist = Db::query($sql, [$uid]);
        $goodslist = array();
        foreach ($orderlist as $v){
            $list = json_decode($v,true);
            $innerGoodsList = array();
            foreach ($list as $lv){
                $innerGoodsList[] = array(
                    'gid' =>  $lv['gid'],
                    'img' =>  $lv['img'],
                    'name' =>  $lv['name'],
                    'code' =>  $lv['code'],
                    'price' =>  $lv['price'],
                    'count' =>  $lv['count'],
                    'origin' =>  '商城',
                    'create_time' =>  $lv['create_time'],
                    'parcel' =>  $lv['parcel'],
                    'order_no' =>  $lv['order_no'],
                    'order_id' =>  $lv['order_id'],
                );

            }
            $goodslist = array_merge($goodslist,$innerGoodsList);
        }
        return $goodslist;
    }

    /** 获取我的抢购的提货商品 */
    public function getMyRushGoods($uid)
    {
        $sql = "SELECT a.id as order_id,a.order_no,a.gid,a.g_count count,b.name,b.code,b.img,a.create_time,a.g_price price,'抢购' origin,c.parcel  
    FROM sy_goods_rush b 
    LEFT JOIN sy_user_order a ON b.current_order_id=a.id AND a.state=1 AND a.pay_state=1 
    LEFT JOIN sy_user_parcel c ON c.order_from=2 AND c.order_id=a.id
    WHERE b.belong=? AND b.state=6";
        return Db::query($sql, [$uid]);
    }

}